package leecode

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/segmentio/kafka-go"
	"time"
)

type Message struct {
	From    int
	To      int
	Type    int
	Time    string
	Content string
}

func main() {
	message := Message{
		From:    1,
		To:      10,
		Type:    1,
		Time:    "123",
		Content: "你好，张斌之",
	}
	WriteByConn(message)
}

// WriteByConn 基于conn发送消息
func WriteByConn(message Message) {
	topic := "user"
	host := "114.55.135.211:9092"
	partition := int(message.To)

	conn, _ := kafka.DialLeader(context.Background(), "tcp", host, topic, partition)
	conn.SetWriteDeadline(time.Now().Add(10 * time.Second))

	jsonMessage, _ := json.Marshal(message)
	_, err := conn.WriteMessages(kafka.Message{Value: jsonMessage})
	if err != nil {
		fmt.Println(err)
	}
	defer conn.Close()
}
